<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <!-- 搜索结果后,再次输入不会显示联想建议 用focus事件来将搜索结果隐藏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
      <!-- 搜索结果 -->
      <searchResult v-if="isResultShow" :searchText="searchText"></searchResult>
      <!-- 搜索联想建议 根据输入框是否有值决定联想建议的显示 -->
      <!-- 将输入框里的值传给子组件,监听变化并请求数据 -->
      <searchSuggestion
        v-if="searchText"
        :searchText="searchText"
      ></searchSuggestion>
      <!-- 搜索历史 -->
      <searchHistory
        v-else
        :searchHistories="searchHistories"
        @delAllHistorys="searchHistories = []"
        @search="onSearch"
      ></searchHistory>
    </form>
  </div>
</template>

<script>
import searchHistory from "./components/search-history.vue";
import searchSuggestion from "./components/search-suggestion.vue";
import searchResult from "./components/search-result.vue";
import { getItem, setItem } from "@/utils/storage";
export default {
  name: "SearchIndex",
  data() {
    return {
      searchText: "", //监听搜索框的输入值
      isResultShow: false, //控制搜索结果的显示状态
      searchHistories: getItem("TOUTIAO_SEARCH_HISTORY") || [], //搜索历史
    };
  },
  methods: {
    // 用过搜索事件
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;
      // indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。没找到返回-1
      let res = this.searchHistories.indexOf(val);
      //  如果val在历史中 先删除旧的 在unshift新的进数组
      if (res !== -1) {
        this.searchHistories.splice(res, 1);
      }
      this.searchHistories.unshift(val);
    },
    // 取消 返回上一页
    onCancel() {
      this.$router.back();
    },
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult,
  },
  watch: {
    searchHistories(val) {
      setItem("TOUTIAO_SEARCH_HISTORY", val);
    },
  },
};
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
